import { ConfigEnv, loadEnv, UserConfig } from "vite";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ArcoResolver } from "unplugin-vue-components/resolvers";
import vue from "@vitejs/plugin-vue";
import path from "node:path";
const CWD = process.cwd();
import dayjs from "dayjs";

export default ({ mode }: ConfigEnv): UserConfig => {
  const { VITE_BASE_URL, VITE_API_URL_PREFIX } = loadEnv(mode, CWD);
  // 获取构建时间戳
  const buildTime = dayjs().format("YYYY-MM-DDTHHmmss");

  return {
    base: VITE_BASE_URL,
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ArcoResolver()],
      }),
      Components({
        resolvers: [
          ArcoResolver({
            sideEffect: true,
          }),
        ],
      }),
    ],
    server: {
      host: "0.0.0.0",
      port: 3002,
      open: false, // 设置服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      proxy: {
        [VITE_API_URL_PREFIX]: {
          // target: "http://127.0.0.1:8080",
          target: "https://api.znpaizuo.com",
          changeOrigin: true,
          secure: false,
          rewrite: (path: string) => path.replace(VITE_API_URL_PREFIX, ""),
        },
      },
    },
    build: {
      rollupOptions: {
        output: {
          // 启用文件名哈希
          entryFileNames: `assets/[name]-[hash]-${buildTime}.js`,
          chunkFileNames: "assets/[name]-[hash].js",
          assetFileNames: "assets/[name]-[hash].[ext]",
        },
      },
    },
    define: {
      __BUILD_TIME__: JSON.stringify(buildTime),
    },
  };
};
